package com.atguigu.acl.service.impl;

import com.atguigu.acl.entity.Permission;
import com.atguigu.acl.mapper.PermissionMapper;
import com.atguigu.acl.service.PermissionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 权限 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-07-18
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Override
    public List<Permission> getAllMenu() {
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("pid");
        List<Permission> permissionList = baseMapper.selectList(wrapper);

//        最终结果

//      开始构建层级菜单
        List<Permission> finalList = new ArrayList<>();
        for (Permission permission : permissionList) {
//            寻找初始父节点
            if ("0".equals(permission.getPid())) {
//                初始父节点为1级菜单
                permission.setLevel(1);
                Permission node = getNode(permission, permissionList);
                finalList.add(node);
            }
        }
//    返回最终数据
        return finalList;
    }

    /**
     * 获取其他节点
     *
     * @param permission
     * @param permissionList
     * @return
     */
    private Permission getNode(Permission permission, List<Permission> permissionList) {
        permission.setChildren(new ArrayList<>());
        for (Permission permissionNode : permissionList) {
//            子节点的parentId 与父节点id相同
            if (permission.getId().equals(permissionNode.getPid())) {
//                层级+1
                Integer level = permission.getLevel() + 1;
                permissionNode.setLevel(level);

                if (permission.getChildren() == null) {
                    permission.setChildren(new ArrayList<>());
                }
                permission.getChildren().add(getNode(permissionNode, permissionList));
            }
        }
        return permission;
    }

}
